package org.codingq92.basic.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class CusAQS {
    public static void main(String[] args) throws InterruptedException {
        int[] nums = new int[]{1000};
        List<Thread> threads = new ArrayList<>();
        MyAQS myAQS = new MyAQS();
        for (int i = 0; i < 1000; i++) {
            threads.add(new Thread(() -> {
                try {
                    myAQS.lock();
                    try {
                        TimeUnit.MICROSECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    nums[0]--;
                } finally {
                    myAQS.unLock();
                }
            }));
        }
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        System.out.println(nums[0]);
    }

    // 自定义aqs
    static class MyAQS {
        private static final AtomicBoolean state = new AtomicBoolean(false);

        void lock() {
            while (true) {
                if (state.compareAndSet(false, true)) {
                    return;
                }
            }
        }

        void unLock() {
            while (true) {
                if (state.compareAndSet(true, false)) {
                    return;
                }
            }
        }
    }
}
